<script setup lang="ts">
    import { toRefs, defineProps, ref, inject, getCurrentInstance } from 'vue';
    import { ImgPreviews } from '@/services/type';
    import { useUserStore } from '@/stores/user';
    import { api } from '@/services/api';

    import 'vue-cropper/dist/index.css';
    import { VueCropper } from "vue-cropper";

    const cropperRef = ref();
    const internalInstance = getCurrentInstance();
    const userStore = useUserStore();
    const msg: any = inject('message');

    // 属性
    let props = defineProps({
        visible: {
            type: Boolean,
            default: false
        }
    });
    let { visible } = toRefs(props);

    // 参数
    const option = ref({
        size: 1,
        outputType: 'jpeg || png || webp', // 裁剪生成图片的格式
        img: '',
        outputSize: 1, // 裁剪生成图片的质量
        full: false, // 输出原图比例截图 props名full
        autoCrop: true, //    是否默认生成截图框
        canMove: true, // 上传图片是否可以移动
        canMoveBox: true, // 截图框能否拖动
        fixedBox: true, // 固定截图框大小 不允许改变
        original: false, // 上传图片按照原始比例渲染
        autoCropWidth: 60, // 默认生成截图框宽度
        autoCropHeight: 60, // 默认生成截图框高度
        centerBox: false, // 截图框是否被限制在图片里面
        high: true, // 是否按照设备的dpr 输出等比例图片
        infoTrue: true, // true 为展示真实输出图片宽高 false 展示看到的截图框宽高
        enlarge: 1, // 图片根据截图框输出比例倍数
        maxImgSize: 2000, // 限制图片最大宽度和高度
        fixed: true, // 是否开启截图框宽高固定比例
        fixedNumber: [1, 1], // 截图框的宽高比例 需要配合centerBox一起使用才能生效 1比1
        info: true,
        mode: '100%'
    })
    // 预览信息
    let previews = ref<Partial<ImgPreviews>>({});

    // 覆盖默认的上传行为
    const requestUpload = () => {}
    // 实时预览
    const realTime = (data: any) => {
        previews.value = data;
    }
    // 上传预处理
    const beforeUpload = (file: File) => {
        if (file.type.indexOf("image/") == -1) {
            msg.info("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        } else {
            const reader = new FileReader();
            reader.readAsDataURL(file);
            reader.onload = () => {
                if(option.value.img != null) {
                    if(reader.result) {
                        const result: string = reader.result.toString();
                        option.value.img = result;
                    }
                }
                
            };
        }
    }
    // 图片缩放
    const changeScale = (i: number) => {
        i = i || 1;
        cropperRef.value.changeScale(i);
    }
    // 向右旋转
    const rotateRight = () => {
        cropperRef.value.rotateRight();
    }
    // 上传头像
    const uploadIcon = () => {
        cropperRef.value.getCropBlob((data: any) => {
            const formData = new FormData();
            formData.append("file", data);
            api.user.uploadIcon(formData).then(response => {
                if(response.code === 0) {
                    const img = window.URL.createObjectURL(data);
                    if(internalInstance) {
                        internalInstance.emit("close");
                    }
                    userStore.userInfo.avatar = img;
                    msg.success("上传成功");
                }
            });
        });
    }

</script>
<template>
    <el-dialog title="上传头像" v-model="visible" width="420" draggable :lock-scroll="false" :close-on-click-modal="false">
        <div class="update-user-icon">
            <el-row>
                <el-col :xs="24" :md="17" :style="{height: '250px'}">
                    <VueCropper
                        ref="cropperRef"
                        :img="option.img"
                        :outputSize="option.outputSize"
                        :outputType="option.outputType"
                        :info="option.info"
                        :full="option.full"
                        :canMove="option.canMove"
                        :canMoveBox="option.canMoveBox"
                        :fixedBox="option.fixedBox"
                        :original="option.original"
                        :autoCrop="option.autoCrop"
                        :autoCropWidth="option.autoCropWidth"
                        :autoCropHeight="option.autoCropHeight"
                        :centerBox="option.centerBox"
                        :high="option.high"
                        :infoTrue="option.infoTrue"
                        :enlarge="option.enlarge"
                        :fixed="option.fixed"
                        :fixedNumber="option.fixedNumber"
                        :mode="option.mode"
                        @realTime="realTime"
                    />
                </el-col>
                <el-col :xs="24" :md="7" :style="{height: '250px'}">
                    <div class="container">
                        <div class="title">
                            <span>图片预览:</span>
                        </div>
                        <div class="avatar-upload-preview">
                            <img :src="previews.url" :style="previews.img" />
                        </div>
                        <div class="upload">
                            <el-button type="primary" @click="uploadIcon">提 交</el-button>
                        </div>
                    </div>
                </el-col>
            </el-row>
            <el-row style="margin-top: 10px;">
                <el-col :xs="24" :md="14">
                    <div class="oper-box">
                        <el-upload 
                            action="#" 
                            :http-request="requestUpload" 
                            :show-file-list="false" 
                            :before-upload="beforeUpload"
                        >
                            <a>选择头像</a>
                        </el-upload>
                    </div>
                </el-col>
                <el-col :xs="24" :md="1" style="text-align: center">
                    <div class="oper rotate_right" @click="changeScale(1)"><el-icon><CirclePlus /></el-icon></div>
                </el-col>
                <el-col :xs="24" :md="1" style="text-align: center">
                    <div class="oper rotate_right" @click="changeScale(-1)"><el-icon><Remove /></el-icon></div>
                </el-col>
                <el-col :xs="24" :md="1" style="text-align: center">
                    <div class="oper refresh_right" @click="rotateRight()"><el-icon><RefreshRight /></el-icon></div>
                </el-col>
            </el-row>
        </div>
    </el-dialog>
</template>
<!-- 引入样式文件 -->
<!-- <style lang="less" src="./style.less" scoped /> -->
<style scoped>
    .container {
        margin-left: 20px;
    }

    .title {
        font-size: 16px;
        font-weight: bolder;
    }

    .oper {
        cursor: pointer;
    }

    .avatar-upload-preview {
        -webkit-transform: translate(50%,-50%);
        transform: translate(50%,-50%);
        width: 60px;
        height: 60px;
        border-radius: 50%;
        -webkit-box-shadow: 0 0 4px #ccc;
        box-shadow: 0 0 4px #ccc;
        overflow: hidden;
        margin-top: 35px;
        margin-left: -30px;
    }

    a {
      color: #337ab7;
    }

</style>